#laravel markdown mail
Explore tagged Tumblr posts
wamasoftwareindia · 2 years ago
Text
Expert Laravel Developer
We have a team of expert Laravel developers with incredible experience behind them. They effectively convey Laravel-put together modified site development solutions concerning customer requirements and contract Laravel Framework developers with our organization as we encourage organizations and web advancement firms to improve primary concern results.
One of the leading Laravel Development companies, analyzes an agile methodology technique with Laravel-based solutions that assist in making applications that meet the explicit client, business, industry and vertical needs. Our Laravel developrs offer remarkable understanding that underpins almost every part of your Laravel bundle improvement, ideal from counselling to methodology.
Hire Laravel Developer
Hire Laravel consultants who are talented in working on Laravel's sophisticated features like collections to encourage shortcuts for everyday actions, Blade Components and Slots for creating templates. When you hire Laravel developer services, you get Real-Time Facades to minimize the lines of code to convert class to facade, Markdown Mail & Notification - a pre-defined template used for mailing features, Laravel Dusk - a browser testing tool and Other advanced features are also used.
For more information visit us our website : wama software
0 notes
codingspoint · 3 years ago
Text
How to Send Email by using Markdown Mailables in Laravel 9?
How to Send Email by using Markdown Mailables in Laravel 9?
Today now in this article i will give you an example of laravel 9 send mail by using markdown mail. Here I would like to show you an example of laravel 9 mail send markdown. Here we will use the laravel 9 send email by using markdown. It’s a very simple example of laravel 9 sending mail by using mailable. We know that Laravel 9 Markdown is provides the inbuilt pre-define mail templates and also…
View On WordPress
0 notes
meetloading354 · 4 years ago
Text
Visual Studio Laravel
Tumblr media
Visual Studio Laravel
Search results for 'laravel', Visual Studio Code on marketplace.visualstudio.com. Out of the blue, Microsoft jumps into the editor wars with an incredible offering that gives Sublime Text an overwhelming run for its money. In fact, it just might surpass it! So come along, as I demonstrate the ins, the outs, the tips, the techniques. Say hello to your new best friend: Visual Studio Code. Laravel Intellisense is a Visual Studio Code plugin by Mohamed Benhida that provides some nice auto-completion for things like Eloquent models, factories, config, and API resources. The extension works only on Laravel projects and a project is considered a Laravel project only if there is an artisan file in the root directory. Gaurav Makhecha; Credits. PHP Parser by Glayzzle. Currently, you're free to use this extension. I would highly appreciate you buying the world a.
Tumblr media
Visual Studio Laravel
Travel through your Laravel app by just clicking on links.
Features
Open Latest Log File
Open latest log file from anywhere. Select the Command Laravel Traveller: Open Latest Log File or press Ctrl+o Ctrl+l (Cmd+o Cmd+l for Mac). You can change the default keyboard shortcut as well.
Technical Notes
The following glob pattern is used to search log files: 'storage/logs/laravel*.log'
Route -> Controller
Link to controller + action from the routes files:
Link to controller + action as per route group namespace:
You can add a simple comment // Route::namespace = NAMESPACE to apply group namespace on file. For example, the routes/api.php in the Laravel app has Api namespace applied by default.
Technical Notes
The controller links are added only in the files that are inside /routes directory or sub-directories and end with .php
php-parser by glayzzle is being used to get the AST of the file and add links based on that.
We consider only the static calls to Route::(get/post/put/patch/delete) and add links to the second parameter of those calls.
We suggest you to write route groups like: Route::namespace('Admin')->group(function() (..)) (as per Laravel documentation) instead of Route::group(('namespace' => 'Admin'), function() (..)) (namespace not supported by extension this way).
Automatic Controller Creation
If the controller does not exist, you'll be asked whether the extension should create it for you automatically. Action method will also be added to the controller. If you want to customize the stub that is used to create the controller, Add stubs/controller.plain.stub to your project's root directory. Please check the Stub Customization section of the Laravel documentation for instructions.
Technical Notes
For automatic controller creation, the default namespace is set to AppHttpControllers.
Automatic Method Creation
If the method does not exist, you'll be asked whether the extension should create it for you automatically. If you want to customize the stub that is used to create the method, Add stubs/method.stub to your project's root directory. (( methodName )) placeholder will be replaced with the actual method name.
Technical Notes
php-parser by glayzzle is being used to get the AST of the controller file and add the method to the end of the file. Basic expectations are that there will be a namespace at the top, a class, and at least 1 method in the controller file.
Controller -> View
Link to blade views from the controllers:
Technical Notes
The view links are added only in the files that are inside /app/Http/Controllers directory or sub-directories and end with .php
It uses this regex to find lines with view helper: ^s*return view((')(https://github.com/freshbitsweb/laravel-traveller/blob/master/.*?)(').*).*$
Currently, it links to the blade files in resources/views directory.
Mailable -> View
Link to blade views from the Mail classes:
Technical Notes
The view or markdown links are added only in the files that are inside /app/Mail directory or sub-directories and end with .php
It uses this regex to find lines with view or markdown method call: ^.*->(?:view|markdown)((')(https://github.com/freshbitsweb/laravel-traveller/blob/master/.*?)(').*).*$
Currently, it links to the blade files in resources/views directory.
View -> View
Link to blade views from the blade view:
Technical Notes
The view or markdown links are added only in the files that are inside /resources/views directory or sub-directories and end with .blade.php
It uses this regex to find lines with view or markdown method call: ^.*@(?:extends|include)((')(https://github.com/freshbitsweb/laravel-traveller/blob/master/.*?)(').*).*$
Currently, it links to the blade files in resources/views directory.
Route -> View
Link to blade views from the Route files:
Technical Notes
The view links are added only in the files that are inside /routes directory or sub-directories and end with .php
php-parser by glayzzle is being used to get the AST of the file and add links based on that.
Currently, it links to the blade files in resources/views directory.
Model -> Model
Link to models from the related model files:
Technical Notes
The model links are added only in the files that are inside /app directory and end with .php. and links to models in app directory only.
It uses this regex to find lines with relationship calls: ^s*return $this->(?:hasOne|belongsTo|hasMany|belongsToMany|morphOne|morphMany)((')(https://github.com/freshbitsweb/laravel-traveller/blob/master/.*?)(').*$
Route -> Route
Link to other routes from route files:
Technical Notes
The route links are added only in the files that are inside /routes directory and end with .php.
The definitions needs to be in this format: Route::group((), base_path('(ROUTE_FILE_PATH)'));
Configuration
5 of the features: Route -> Controller, Controller -> View, Mailable -> View, View -> View, and Model -> Model are toggelable: You can disable them from VSCode settings if you do not need them.
Technical Notes
The extension works only on Laravel projects and a project is considered a Laravel project only if there is an artisan file in the root directory.
Authors
Credits
Treeware
Currently, you're free to use this extension. I would highly appreciate you buying the world a tree in return.
Evernote is chinese app store. It’s now common knowledge that one of the best tools to tackle the climate crisis and keep our temperatures from rising above 1.5C is to plant trees. If you contribute to our forest you’ll be creating employment for local families and restoring wildlife habitats.
WPS Office for Mac. WPS PDF to Word 40.3MB. WPS Office For Linux. WPS Data Recovery Master 5.5MB. WPS Office For Android. WPS Office For iOS. WPS PDF For Android. PDF Editor For Android. PDF Converter Pro For Android. WPS Fill & Sign. Wps english download. Download WPS A new generation of office solutions With PDF, Cloud, OCR, file repair, and other powerful tools, WPS Office is quickly becoming more and more people’s first choice in office software.
You can buy trees at for our forest here offset.earth/treeware
To use Astropad Studio you will need to make a user account. Creating a user account is easy, by entering your email and making a password. Your user license for Astropad Studio will be tied to this account. To enter Studio, log in to your user account through your iPad. Luna Display turns any Mac or iPad into a wireless second display for Mac. Makers of Astropad Studio and Luna Display. Turn your iPad into a drawing tablet with Astropad Studio. Extend your Mac display to any iPad or Mac with Luna Display. Astropad. Enjoy a 30-day free trial! Pick a payment plan to get started.
Notes on silencing. Read more about Treeware at treeware.earth
Special Thanks to
Laravel Community
VS Code Community
Tumblr media
0 notes
resourcifi-blog · 6 years ago
Text
What Laravel 5.8 Has To Offer?
With so many options available, selecting the right PHP framework to build a web application for your business can be a challenging task. Laravel has received tremendous popularity over the last few years and Laravel developers are using this framework for a variety of its amazing features and capabilities. A recent update to Laravel was introduced on Feb 26, 2019. Laravel 5.8 introduces new challenges that developers will need to become up-to-date with. This article will look at some of them.
Cache TTL In Seconds - In order to allow a more granular expiration time when storing items, the cache item time-to-live has been changed from minutes to seconds. The “put”, “putMany”, “add”, “remember” and “setDefaultCacheTime” methods of the “Illuminate\Cache\Repository” class and its extended classes, as well as the “put” method of each cache store are updated with the change.
Cache Lock Safety Improvements - In Laravel 5.7 and other older versions of Laravel, the atomic lock feature provided by some cache drivers was reported to have unexpected behavior, which led to the early release of locks. This scenario has been mitigated in the new version 5.8 as locks are now generated with an embedded "scope token". This allows the framework to make sure that, under normal circumstances; a lock can only be released by the proper owner.
Markdown File Directory Change - If a Laravel developer has published Laravel's Markdown mail components using the “vendor:publish” command, they should rename the /resources/views/vendor/mail/markdown directory to text. In addition to that, “textComponentPaths” is the the new name for “markdownComponentPaths” method. To override it, Laravel developers should update the method name to match its parent.
Environment Variable Parsing - The phpdotenv package that is used to parse “.env” files has released a new major upgrade, which may impact the results returned from the .env helper. One important thing to note here is that the “#” character in an unquoted value will now be considered a comment instead of part of the value.
Nexmo / Slack Notification Channels - The Slack and Nexmo Notification channels have been extracted into first-party packages. For dedicated Laravel developers to use these channels in the application, they require the following packages:
composer require laravel/slack-notification-channel composer require laravel/nexmo-notification-channel
Reasons to hire a dedicated Laravel developer:-
Laravel makes implementation of authentication techniques very easy.
The framework has Object Oriented libraries and many other pre-installed ones, which are not usually found in many other PHP frameworks.
Laravel provides a built-in tool for command-line called Artisan that allows Laravel developers to execute the majority of those repetitive and tedious programming tasks with ease.
Laravel supports MVC that helps in improving performance
Looking to hire a Laravel developer for your business website? Partner with Resourcifi - a custom mobile app and web application development company.
0 notes
katyslemon · 4 years ago
Text
Laravel Mail Example: How to Send an Email using Markdown Template in Laravel 8?
Quick Summary
Sending an email is one most important features of any project. In this tutorial, you will learn how to send emails using Markdown Template with the help of Laravel Mail Example. Implementation of the Markdown template is not a difficult task. Yes, you heard it correctly! But, still you haven’t played around it, here’s a step-by-step tutorial, that will provide you with instructions for sending an email using Markdown.
Tutorial Goal: Laravel Mail Example using Markdown Template
Before diving into building a demo application, let’s see this video to clarify what we are building here.
youtube
The user will enter the name and email address, and after clicking on submit button, an email will be sent to the entered email address. Login to that email address, and there you can see the email.
Step-by-step guidelines: Laravel Mail Example: How to Send an Email using Markdown Template in Laravel 8?
Tumblr media
Learn more: Laravel Mail Example Using Markdown
0 notes
Text
Laravel Mail Example: How to Send an Email using Markdown Template in Laravel 8?
Sending an email is one of the most important functions of any project. This tutorial will show you how to use the Laravel mail example to send an email using a Markdown template. Markdown templates are not challenging to implement. This is a step-by-step guide that will guide you through using Markdown to send emails.
Step-by-step guidelines: Laravel Mail Example: How to Send an Email using Markdown Template in Laravel 8?
Tumblr media
Step 1: Create Laravel Project
Step 2: Configuration Setup.
Step 3: Create Mail with Markdown.
Step 4: Create a Controller for Mail.
Step 5: Create a simple form
Read More in Laravel mail example using markdown
0 notes
itsmetacentric · 5 years ago
Link
laravel 5 8 send email,laravel 5 send email example,markdown laravel 7/6 mail, markdown laravel 7/6 email, laravel 7/6 markdown components, laravel 7/6 send email mailable, laravel 7/6 send email markdown, laravel 7/6 send mail mailable, laravel 7/6 send mail using mailable
0 notes
programmingbiters-blog · 7 years ago
Photo
Tumblr media
New Post has been published on https://programmingbiters.com/laravel-5-mail-notifications-using-customized-templates/
Laravel 5 Mail Notifications using Customized Templates
Laravel has a useful Notification system, where you can notify user about something via email, Slack etc. And there is a quite good default HTML template for emails. But what if you want to customize its design?
This is the template I’m talking about:
Let’s remind ourselves how to send this email.
1
2
3
php artisan make:notification HelloUser
It will generate class app/Notifications/HelloUser.php – here’s the main part of it:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class HelloUser extends Notification
    public function via($notifiable)
             return [‘mail’];
         public function toMail($notifiable)
             return (new MailMessage)
                    ->line(‘The introduction to the notification.’)
                    ->action(‘Notification Action’, url(‘/’))
                    ->line(‘Thank you for using our application!’);
     By default, notification channel is mail, and there is some default email constructed.
You build the email text by using methods like ->line() or ->action(), and actually in the back-end it fills in a beautiful HTML template.
How to fire this notification?
1
2
3
4
$user = User::first(); // or any other way you get User instance
$user->notify(new HelloUser());
Now, we didn’t edit any Blade template or any HTML, where to find it? It’s not that easy, by default it’s not in resources/views anywhere. You need to publish the templates, like this:
1
2
3
php artisan vendor:publish —tag=laravel–notifications
Result: Copied Directory [/vendor/laravel/framework/src/Illuminate/Notifications/resources/views] To [/resources/views/vendor/notifications]
So before you publish – the template is inside of Laravel core in /vendor folder (which you shouldn’t edit, ever). And now – we can modify our HTML.
In fact, there’s only one published template – file resources/views/vendor/notifications/email.blade.php:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
@component(‘mail::message’)
— Greeting —
@if (! empty($greeting))
# $greeting
@else
@if ($level == ‘error’)
# Whoops!
@else
# Hello!
@endif
@endif
— Intro Lines —
@foreach ($introLines as $line)
$line
@endforeach
— Action Button —
@isset($actionText)
<?php
    switch ($level)
        case ‘success’:
            $color = ‘green’;
            break;
        case ‘error’:
            $color = ‘red’;
            break;
        default:
            $color = ‘blue’;
     ?>
@component(‘mail::button’, [‘url’ => $actionUrl, ‘color’ => $color])
$actionText
@endcomponent
@endisset
— Outro Lines —
@foreach ($outroLines as $line)
$line
@endforeach
— Salutation —
@if (! empty($salutation))
$salutation
@else
Regards,<br> config(‘app.name’)
@endif
— Subcopy —
@isset($actionText)
@component(‘mail::subcopy’)
If you’re having trouble clicking the “ $actionText ” button, copy and paste the URL below
into your web browser: [ $actionUrl ]( $actionUrl )
@endcomponent
@endisset
@endcomponent
But wait, you will say – where’s all the HTML?? It’s hiding under another layer – Laravel’s notification components based on Markdown language.
There are three components, mentioned in the official Laravel docs:
1. Button:
1
2
3
4
5
@component(‘mail::button’, [‘url’ => $url, ‘color’ => ‘green’])
View Invoice
@endcomponent
2. Panel:
1
2
3
4
5
@component(‘mail::panel’)
This is the panel content.
@endcomponent
3. Table:
1
2
3
4
5
6
7
8
@component(‘mail::table’)
| Laravel       | Table         | Example  |
| ——————– |:——————–:| ————:|
| Col 2 is      | Centered      | $10      |
| Col 3 is      | Right–Aligned | $20      |
@endcomponent
And yes, you can write Markdown instead of HTML, it may be a convenient thing for some people (developers, mostly).
But if you do want to get HTML and be able to edit it, run this:
1
2
3
php artisan vendor:publish —tag=laravel–mail
This will happen: Copied Directory [/vendor/laravel/framework/src/Illuminate/Mail/resources/views] To [/resources/views/vendor/mail]
This is what we get then:
Now it looks really familiar and we can, for example, go to button.blade.php and add some class or text:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<table class=“action” align=“center” width=“100%” cellpadding=“0” cellspacing=“0”>
    <tr>
        <td align=“center”>
            <table width=“100%” border=“0” cellpadding=“0” cellspacing=“0”>
                <tr>
                    <td align=“center”>
                        <table border=“0” cellpadding=“0” cellspacing=“0”>
                            <tr>
                                <td>
                                    <a href=“ $url ” class=“button button- $color or ‘blue’ ” target=“_blank”> $slot </a>
                                </td>
                            </tr>
                        </table>
                    </td>
                </tr>
            </table>
        </td>
    </tr>
</table>
We change  $slot  into Click here: $slot  and we get this email:
Finally, you can even have THEMES with different CSS styles for each of them – like, for example, different emails for different user groups.
For that, there’s a folder resources/views/mail/html/themes with a CSS file, and you can change the default them in config/mail.php:
1
2
3
4
5
6
7
8
9
    ‘markdown’ => [
        ‘theme’ => ‘default’,
        ‘paths’ => [
            resource_path(‘views/vendor/mail’),
        ],
    ],
So this is how to customize Laravel email notifications. You can find more information in the official documentation.
0 notes
mbaljeetsingh · 7 years ago
Text
How to Send Emails in Laravel
In this article, we're going to explore the Mail API in the Laravel web framework. Laravel takes advantage of the popular SwiftMailer library, which is easy to use and comes with a variety of email drivers to choose from. In the latter stages of the article, we'll go through an in-depth demonstration of the concepts discussed in the first half of the article.
Setting Up the Prerequisites
Laravel implements a wrapper on top of the SwiftMailer library that makes email management very easy to configure and use at the same time. You can find the default mail settings at config/mail.php.
<?php return [ /* |-------------------------------------------------------------------------- | Mail Driver |-------------------------------------------------------------------------- | | Laravel supports both SMTP and PHP's "mail" function as drivers for the | sending of e-mail. You may specify which one you're using throughout | your application here. By default, Laravel is setup for SMTP mail. | | Supported: "smtp", "sendmail", "mailgun", "mandrill", "ses", | "sparkpost", "log", "array" | */ 'driver' => env('MAIL_DRIVER', 'sendmail'), /* |-------------------------------------------------------------------------- | SMTP Host Address |-------------------------------------------------------------------------- | | Here you may provide the host address of the SMTP server used by your | applications. A default option is provided that is compatible with | the Mailgun mail service which will provide reliable deliveries. | */ 'host' => env('MAIL_HOST', 'smtp.mailgun.org'), /* |-------------------------------------------------------------------------- | SMTP Host Port |-------------------------------------------------------------------------- | | This is the SMTP port used by your application to deliver e-mails to | users of the application. Like the host we have set this value to | stay compatible with the Mailgun e-mail application by default. | */ 'port' => env('MAIL_PORT', 587), /* |-------------------------------------------------------------------------- | Global "From" Address |-------------------------------------------------------------------------- | | You may wish for all e-mails sent by your application to be sent from | the same address. Here, you may specify a name and address that is | used globally for all e-mails that are sent by your application. | */ 'from' => [ 'address' => env('MAIL_FROM_ADDRESS', '[email protected]'), 'name' => env('MAIL_FROM_NAME', 'Example'), ], /* |-------------------------------------------------------------------------- | E-Mail Encryption Protocol |-------------------------------------------------------------------------- | | Here you may specify the encryption protocol that should be used when | the application send e-mail messages. A sensible default using the | transport layer security protocol should provide great security. | */ 'encryption' => env('MAIL_ENCRYPTION', 'tls'), /* |-------------------------------------------------------------------------- | SMTP Server Username |-------------------------------------------------------------------------- | | If your SMTP server requires a username for authentication, you should | set it here. This will get used to authenticate with your server on | connection. You may also set the "password" value below this one. | */ 'username' => env('MAIL_USERNAME'), 'password' => env('MAIL_PASSWORD'), /* |-------------------------------------------------------------------------- | Sendmail System Path |-------------------------------------------------------------------------- | | When using the "sendmail" driver to send e-mails, we will need to know | the path to where Sendmail lives on this server. A default path has | been provided here, which will work well on most of your systems. | */ 'sendmail' => '/usr/sbin/sendmail -bs', /* |-------------------------------------------------------------------------- | Markdown Mail Settings |-------------------------------------------------------------------------- | | If you are using Markdown based email rendering, you may configure your | theme and component paths here, allowing you to customize the design | of the emails. Or, you may simply stick with the Laravel defaults! | */ 'markdown' => [ 'theme' => 'default', 'paths' => [ resource_path('views/vendor/mail'), ], ], ];
When it comes to sending mails, Laravel supports different drivers to choose from. As you can see, the default MAIL_DRIVER is set to smtp.
If you are going to use the smtp driver to send mails then you're also required to set other related settings like MAIL_HOST, MAIL_PORT, MAIL_ENCRYPTION, MAIL_USERNAME, and MAIL_PASSWORD.
On the other hand, if you are going to use the sendmail driver, then you want to make sure that the sendmail system path is set to the correct value in the config/mail.php file.
You can also set the from address that will be used while sending mails under the from key. And finally, if you want to use Markdown-based email rendering, you can set those settings under the markdown key.
The cherry on the top is that you could also use third-party email service providers like Mailgun, Mandrill, SES, and SparkPost. If you are using one of those services, you need to make sure that you set the corresponding settings in the config/services.php file.
So that was a basic introduction to the mail API related settings in Laravel. From the next section onwards, we'll go through a custom example that shows you how to send emails.
Create the Mailable Class
In this section, we'll create the mailable class, which will be used to send emails. The mailable class is responsible for sending emails using a mailer that's configured in the config/mail.php file. In fact, Laravel already provides an artisan command that allows us to create a base template.
php artisan make:mail DemoEmail
That should create a blank email template at app/Mail/DemoEmail.php, as shown in the following snippet.
<?php namespace App\Mail; use Illuminate\Bus\Queueable; use Illuminate\Mail\Mailable; use Illuminate\Queue\SerializesModels; use Illuminate\Contracts\Queue\ShouldQueue; class DemoEmail extends Mailable { use Queueable, SerializesModels; /** * Create a new message instance. * * @return void */ public function __construct() { // } /** * Build the message. * * @return $this */ public function build() { return $this->view('view.name'); } }
Let's replace the contents of that file with the following.
<?php namespace App\Mail; use Illuminate\Bus\Queueable; use Illuminate\Mail\Mailable; use Illuminate\Queue\SerializesModels; use Illuminate\Contracts\Queue\ShouldQueue; class DemoEmail extends Mailable { use Queueable, SerializesModels; /** * The demo object instance. * * @var Demo */ public $demo; /** * Create a new message instance. * * @return void */ public function __construct($demo) { $this->demo = $demo; } /** * Build the message. * * @return $this */ public function build() { return $this->from('[email protected]') ->view('mails.demo') ->text('mails.demo_plain') ->with( [ 'testVarOne' => '1', 'testVarTwo' => '2', ]) ->attach(public_path('/images').'/demo.jpg', [ 'as' => 'demo.jpg', 'mime' => 'image/jpeg', ]); } }
There are two important methods the mailable class generally implements—__construct and build. The __construct method is used to initialize objects that you're supposed to use in the email template. On the other hand, the build method is used to initialize more email-specific values like from, view template, attachments and similar.
In our case, we've passed the $demo object as a constructor argument, and it's assigned to the demo public property.
In the build method, we've initialized an email-specific configuration.
The from is used to set an email address that'll be used as a from address.
Using the view method, you can set the email template that will be used while sending an email using this mailable. In our case, we've set it to mails.demo, and it means that you need to create a view template file at resources/views/mails/demo.blade.php.
Next, the text method is used to set up the plain text version of an email template.
As we've just discussed, the __construct method is used to set up objects that'll be used in the email template, you can also use the with method that allows you to set the view data of a message.
Next, we've used the attach method to attach an image with a message.
Of course, we need to create email templates that we're supposed to use while sending emails. Go ahead and create a file resources/views/mails/demo.blade.php as shown in the following snippet.
Hello <i></i>, <p>This is a demo email for testing purposes! Also, it's the HTML version.</p> <p><u>Demo object values:</u></p> <div> <p><b>Demo One:</b> </p> <p><b>Demo Two:</b> </p> </div> <p><u>Values passed by With method:</u></p> <div> <p><b>testVarOne:</b> </p> <p><b>testVarTwo:</b> </p> </div> Thank You, <br/> <i></i>
Also, let's create the plain text version of that file at resources/views/mails/demo_plain.blade.php.
Hello , This is a demo email for testing purposes! Also, it's the HTML version. Demo object values: Demo One: Demo Two: Values passed by With method: testVarOne: testVarOne: Thank You,
So that was the mailable class at your disposal, and we've not done yet as we need to use the Mail facade to actually send mails. In the very next section, we'll explore how you can use the Mail Facade to send emails using the DemoEmail Mailable class that was just created in this section.
Wrapping Up
In this section, we'll create an example to demonstrate how you can use the Mailable class that was created in the last section.
Let's create a controller file at app/Http/Controllers/MailController.php with the following contents.
<?php namespace App\Http\Controllers; use App\Http\Controllers\Controller; use App\Mail\DemoEmail; use Illuminate\Support\Facades\Mail; class MailController extends Controller { public function send() { $objDemo = new \stdClass(); $objDemo->demo_one = 'Demo One Value'; $objDemo->demo_two = 'Demo Two Value'; $objDemo->sender = 'SenderUserName'; $objDemo->receiver = 'ReceiverUserName'; Mail::to("[email protected]")->send(new DemoEmail($objDemo)); } }
It's important to note that we've included the Illuminate\Support\Facades\Mail Facade that will be used to send an email. In the send method, the following statement is responsible for sending an email by initialising the App\Mail\DemoEmail Mailable in the first place.
Mail::to("[email protected]")->send(new DemoEmail($objDemo));
The to method of the Illuminate\Support\Facades\Mail Facade returns an instance of the \Illuminate\Mail\PendingMail class, which already contains an appropriate mailer configured in the config/mail.php file.
And finally, we use the send method of the \Illuminate\Mail\PendingMail class that sends an actual email.
To test it, let's add an associated route in the routes/web.php file.
// Email related routes Route::get('mail/send', 'MailController@send');
And with that in place, you can run the http://ift.tt/2BSrKyg URL to see if it works as expected.
On the other hand, if you want to test your email templates quickly, without sending actual emails, there's a provision in Laravel that allows you to log all outgoing emails.
To achieve that, you need to set the value of MAIL_DRIVER to log in the config/mail.php file. Next, you could run the aforementioned URL and inspect the log file to check if the email template was logged there.
If everything goes fine, you should see an email being logged to the storage/logs/laravel.log file.
That's pretty much it as far as the mail feature is concerned in Laravel, and that concludes this article as well.
Conclusion
Today, we went through the mail API that comes built into Laravel, and it also supports a variety of drivers as well.
Starting with basic concepts, we implemented the mailable class that is an essential element in the mail API in Laravel as we moved on. At the end, we also tested the mailable class by creating a custom controller to see if it actually works.
If you're just getting started with Laravel or looking to expand your knowledge, site, or application with extensions, we have a variety of things you can study in Envato Market.
I would love to know your feedback in the form of queries and comments using the feed below!
via Envato Tuts+ Code http://ift.tt/2lq3bll
0 notes
t-baba · 7 years ago
Photo
Tumblr media
How to Send Emails in Laravel
In this article, we're going to explore the Mail API in the Laravel web framework. Laravel takes advantage of the popular SwiftMailer library, which is easy to use and comes with a variety of email drivers to choose from. In the latter stages of the article, we'll go through an in-depth demonstration of the concepts discussed in the first half of the article.
Setting Up the Prerequisites
Laravel implements a wrapper on top of the SwiftMailer library that makes email management very easy to configure and use at the same time. You can find the default mail settings at config/mail.php.
<?php return [ /* |-------------------------------------------------------------------------- | Mail Driver |-------------------------------------------------------------------------- | | Laravel supports both SMTP and PHP's "mail" function as drivers for the | sending of e-mail. You may specify which one you're using throughout | your application here. By default, Laravel is setup for SMTP mail. | | Supported: "smtp", "sendmail", "mailgun", "mandrill", "ses", | "sparkpost", "log", "array" | */ 'driver' => env('MAIL_DRIVER', 'sendmail'), /* |-------------------------------------------------------------------------- | SMTP Host Address |-------------------------------------------------------------------------- | | Here you may provide the host address of the SMTP server used by your | applications. A default option is provided that is compatible with | the Mailgun mail service which will provide reliable deliveries. | */ 'host' => env('MAIL_HOST', 'smtp.mailgun.org'), /* |-------------------------------------------------------------------------- | SMTP Host Port |-------------------------------------------------------------------------- | | This is the SMTP port used by your application to deliver e-mails to | users of the application. Like the host we have set this value to | stay compatible with the Mailgun e-mail application by default. | */ 'port' => env('MAIL_PORT', 587), /* |-------------------------------------------------------------------------- | Global "From" Address |-------------------------------------------------------------------------- | | You may wish for all e-mails sent by your application to be sent from | the same address. Here, you may specify a name and address that is | used globally for all e-mails that are sent by your application. | */ 'from' => [ 'address' => env('MAIL_FROM_ADDRESS', '[email protected]'), 'name' => env('MAIL_FROM_NAME', 'Example'), ], /* |-------------------------------------------------------------------------- | E-Mail Encryption Protocol |-------------------------------------------------------------------------- | | Here you may specify the encryption protocol that should be used when | the application send e-mail messages. A sensible default using the | transport layer security protocol should provide great security. | */ 'encryption' => env('MAIL_ENCRYPTION', 'tls'), /* |-------------------------------------------------------------------------- | SMTP Server Username |-------------------------------------------------------------------------- | | If your SMTP server requires a username for authentication, you should | set it here. This will get used to authenticate with your server on | connection. You may also set the "password" value below this one. | */ 'username' => env('MAIL_USERNAME'), 'password' => env('MAIL_PASSWORD'), /* |-------------------------------------------------------------------------- | Sendmail System Path |-------------------------------------------------------------------------- | | When using the "sendmail" driver to send e-mails, we will need to know | the path to where Sendmail lives on this server. A default path has | been provided here, which will work well on most of your systems. | */ 'sendmail' => '/usr/sbin/sendmail -bs', /* |-------------------------------------------------------------------------- | Markdown Mail Settings |-------------------------------------------------------------------------- | | If you are using Markdown based email rendering, you may configure your | theme and component paths here, allowing you to customize the design | of the emails. Or, you may simply stick with the Laravel defaults! | */ 'markdown' => [ 'theme' => 'default', 'paths' => [ resource_path('views/vendor/mail'), ], ], ];
When it comes to sending mails, Laravel supports different drivers to choose from. As you can see, the default MAIL_DRIVER is set to smtp.
If you are going to use the smtp driver to send mails then you're also required to set other related settings like MAIL_HOST, MAIL_PORT, MAIL_ENCRYPTION, MAIL_USERNAME, and MAIL_PASSWORD.
On the other hand, if you are going to use the sendmail driver, then you want to make sure that the sendmail system path is set to the correct value in the config/mail.php file.
You can also set the from address that will be used while sending mails under the from key. And finally, if you want to use Markdown-based email rendering, you can set those settings under the markdown key.
The cherry on the top is that you could also use third-party email service providers like Mailgun, Mandrill, SES, and SparkPost. If you are using one of those services, you need to make sure that you set the corresponding settings in the config/services.php file.
So that was a basic introduction to the mail API related settings in Laravel. From the next section onwards, we'll go through a custom example that shows you how to send emails.
Create the Mailable Class
In this section, we'll create the mailable class, which will be used to send emails. The mailable class is responsible for sending emails using a mailer that's configured in the config/mail.php file. In fact, Laravel already provides an artisan command that allows us to create a base template.
php artisan make:mail DemoEmail
That should create a blank email template at app/Mail/DemoEmail.php, as shown in the following snippet.
<?php namespace App\Mail; use Illuminate\Bus\Queueable; use Illuminate\Mail\Mailable; use Illuminate\Queue\SerializesModels; use Illuminate\Contracts\Queue\ShouldQueue; class DemoEmail extends Mailable { use Queueable, SerializesModels; /** * Create a new message instance. * * @return void */ public function __construct() { // } /** * Build the message. * * @return $this */ public function build() { return $this->view('view.name'); } }
Let's replace the contents of that file with the following.
<?php namespace App\Mail; use Illuminate\Bus\Queueable; use Illuminate\Mail\Mailable; use Illuminate\Queue\SerializesModels; use Illuminate\Contracts\Queue\ShouldQueue; class DemoEmail extends Mailable { use Queueable, SerializesModels; /** * The demo object instance. * * @var Demo */ public $demo; /** * Create a new message instance. * * @return void */ public function __construct($demo) { $this->demo = $demo; } /** * Build the message. * * @return $this */ public function build() { return $this->from('[email protected]') ->view('mails.demo') ->text('mails.demo_plain') ->with( [ 'testVarOne' => '1', 'testVarTwo' => '2', ]) ->attach(public_path('/images').'/demo.jpg', [ 'as' => 'demo.jpg', 'mime' => 'image/jpeg', ]); } }
There are two important methods the mailable class generally implements—__construct and build. The __construct method is used to initialize objects that you're supposed to use in the email template. On the other hand, the build method is used to initialize more email-specific values like from, view template, attachments and similar.
In our case, we've passed the $demo object as a constructor argument, and it's assigned to the demo public property.
In the build method, we've initialized an email-specific configuration.
The from is used to set an email address that'll be used as a from address.
Using the view method, you can set the email template that will be used while sending an email using this mailable. In our case, we've set it to mails.demo, and it means that you need to create a view template file at resources/views/mails/demo.blade.php.
Next, the text method is used to set up the plain text version of an email template.
As we've just discussed, the __construct method is used to set up objects that'll be used in the email template, you can also use the with method that allows you to set the view data of a message.
Next, we've used the attach method to attach an image with a message.
Of course, we need to create email templates that we're supposed to use while sending emails. Go ahead and create a file resources/views/mails/demo.blade.php as shown in the following snippet.
Hello <i></i>, <p>This is a demo email for testing purposes! Also, it's the HTML version.</p> <p><u>Demo object values:</u></p> <div> <p><b>Demo One:</b> </p> <p><b>Demo Two:</b> </p> </div> <p><u>Values passed by With method:</u></p> <div> <p><b>testVarOne:</b> </p> <p><b>testVarTwo:</b> </p> </div> Thank You, <br/> <i></i>
Also, let's create the plain text version of that file at resources/views/mails/demo_plain.blade.php.
Hello , This is a demo email for testing purposes! Also, it's the HTML version. Demo object values: Demo One: Demo Two: Values passed by With method: testVarOne: testVarOne: Thank You,
So that was the mailable class at your disposal, and we've not done yet as we need to use the Mail facade to actually send mails. In the very next section, we'll explore how you can use the Mail Facade to send emails using the DemoEmail Mailable class that was just created in this section.
Wrapping Up
In this section, we'll create an example to demonstrate how you can use the Mailable class that was created in the last section.
Let's create a controller file at app/Http/Controllers/MailController.php with the following contents.
<?php namespace App\Http\Controllers; use App\Http\Controllers\Controller; use App\Mail\DemoEmail; use Illuminate\Support\Facades\Mail; class MailController extends Controller { public function send() { $objDemo = new \stdClass(); $objDemo->demo_one = 'Demo One Value'; $objDemo->demo_two = 'Demo Two Value'; $objDemo->sender = 'SenderUserName'; $objDemo->receiver = 'ReceiverUserName'; Mail::to("[email protected]")->send(new DemoEmail($objDemo)); } }
It's important to note that we've included the Illuminate\Support\Facades\Mail Facade that will be used to send an email. In the send method, the following statement is responsible for sending an email by initialising the App\Mail\DemoEmail Mailable in the first place.
Mail::to("[email protected]")->send(new DemoEmail($objDemo));
The to method of the Illuminate\Support\Facades\Mail Facade returns an instance of the \Illuminate\Mail\PendingMail class, which already contains an appropriate mailer configured in the config/mail.php file.
And finally, we use the send method of the \Illuminate\Mail\PendingMail class that sends an actual email.
To test it, let's add an associated route in the routes/web.php file.
// Email related routes Route::get('mail/send', 'MailController@send');
And with that in place, you can run the http://ift.tt/2BSrKyg URL to see if it works as expected.
On the other hand, if you want to test your email templates quickly, without sending actual emails, there's a provision in Laravel that allows you to log all outgoing emails.
To achieve that, you need to set the value of MAIL_DRIVER to log in the config/mail.php file. Next, you could run the aforementioned URL and inspect the log file to check if the email template was logged there.
If everything goes fine, you should see an email being logged to the storage/logs/laravel.log file.
That's pretty much it as far as the mail feature is concerned in Laravel, and that concludes this article as well.
Conclusion
Today, we went through the mail API that comes built into Laravel, and it also supports a variety of drivers as well.
Starting with basic concepts, we implemented the mailable class that is an essential element in the mail API in Laravel as we moved on. At the end, we also tested the mailable class by creating a custom controller to see if it actually works.
If you're just getting started with Laravel or looking to expand your knowledge, site, or application with extensions, we have a variety of things you can study in Envato Market.
I would love to know your feedback in the form of queries and comments using the feed below!
by Sajal Soni via Envato Tuts+ Code http://ift.tt/2lqIYf4
0 notes
laravelvuejs · 6 years ago
Text
Laravel 5.8 Tutorial From Scratch - e19 - Handling a Contact Form Using a Laravel Mailable - Laravel
Laravel 5.8 Tutorial From Scratch – e19 – Handling a Contact Form Using a Laravel Mailable – Laravel
Laravel 5.8 Tutorial From Scratch – e19 – Handling a Contact Form Using a Laravel Mailable – Laravel
[ad_1]
Having a contact form where a user can submit their contact request is a very common thing in today’s modern websites. Follow along as we add a contact form and use a Mailable to send an email.
For the best experience, follow along in our interactive school at https://www.coderstape.com
Res…
View On WordPress
0 notes
mbaljeetsingh · 8 years ago
Text
What Are the New Features in Laravel 5.5?
Laravel 5.5 will require PHP 7.0+. For the features this modern PHP version brings, please see our recap.
Laravel 5.5 will also be the next LTS (Long Term Support) release. This means bugfixes for two years and three years of security updates. That was also the case with Laravel 5.1, but its two-year window of bug fixes is coming to an end this year. Without further ado, let's see what this new version has to offer.
Creating a New Laravel 5.5 Project
Since the release has not yet officially happened, we can install the dev release version by running the command:
laravel new laravel55 --dev cd laravel55 php artisan key:generate
If you prefer not to use the Laravel installer, you can also take the Composer approach:
composer create-project --prefer-dist --stability=dev laravel/laravel:dev-master cd laravel php artisan key:generate
Once we visit the homepage of the newly set up app, we should be greeted with a welcome page similar to what we used to have in previous Laravel versions.
Rendering Mailables to the Browser
I feel this is something that will come in very handy. In the previous Laravel versions, we had to send actual emails or use an email client like Mailtrap to test email layouts, and this wasn't a fun task. This won't be the case any more, as with Laravel 5.5 it's possible to render the email layout to the browser directly.
A quick walkthrough on how to achieve this: let's create a new mailable as well as the email template for our current project:
php artisan make:mail Welcome --markdown=emails.welcome
I prefer the markdown approach since we will get a template with some content already. Let's open our web.php file and create a test route to checkout the email layout:
Route::get('/email', function () { return new App\Mail\Welcome(); });
routes/web.php
By visiting the route /email we should be able to preview the email template:
What's actually going on under the hood is that with Laravel 5.5, the Mailable class implements the Renderable contract which has a render() method. This is the implementation of the render() method inside lluminate/Mail/Mailable.php:
public function render() { Container::getInstance()->call([$this, 'build']); return Container::getInstance()->make('mailer')->render( $this->buildView(), $this->buildViewData() ); }
lluminate/Mail/Mailable.php
This is the method that makes it possible to get a view. Had we tried returning an instance of a class that does not implement the Renderable contract within our routes, we'd get an UnexpectedValueException thrown.
Custom Email Themes
When using Markdown for emails, Laravel will provide a default theme. However, some people may prefer having some custom styling in their email templates for branding purposes.
To use a custom theme for a particular mailable, we first create a custom .css file containing the styles we want:
touch resources/views/vendor/mail/html/themes/custom.css
We then then specify this filename as a property in the Mailable class:
class Welcome extends Mailable { protected $theme = 'custom'; [...] }
app/Mail/Welcome.php
This way, the email layout will be based on the styles we defined in the custom.css file. The good thing with this approach is that we can have different themes for different mailables.
Exception Helper Functions
Laravel 5.5 comes with two exception helper functions which will help us write more expressive code. The two helpers are the throw_if and throw_unless methods. Both take three arguments with the third argument being optional.
Let's look at the different implementations of these exceptions:
$number = 2; throw_if($number !== 3, new NotThreeException('Number is not three')); // or throw_if($number !== 3, NotThreeException::class, 'Number is not three');
With the throw_if helper, an exception will be thrown if the first argument evaluates to true.
Implementing the throw_unless helper is no different from what we did above, the only difference being that an exception will only be thrown if the first argument evaluates to false:
$number = 2; throw_unless($number === 3, new NotThreeException('Number is not three')); // or throw_unless($number === 3, NotThreeException::class, 'Number is not three');
Not the best example, but serves our demonstration purposes.
Introducing the migrate:fresh Command
You've probably found yourself in a situation that required you to rebuild the database. With previous Laravel versions, we achieved this by running the php artisan migrate:refresh command. The migrate:refresh command rolls back all migrations based on what is specified in the down method for each migration file then runs the migrations again:
But you've probably run into issues with this command a couple of times, especially when working with foreign key constraints or say you have a down() method in one of your migrations that has not been well defined. When that happens, we resort to dropping the table raising issues manually most of the time - (could be from the CLI or some GUI). That's where migrate:fresh comes to our rescue. This command drops all the tables, then runs the existing migrations again:
JSON Error Stack Traces
Not a really big change but then in previous Laravel versions, we'd see HTML markup from an API client such as Postman every time we got an error while building out APIs. In Laravel 5.5, we get a JSON stack trace rather than HTML markup if an error occurs which looks neater and easier to follow:
Automatic Package Discovery
These are the steps we follow in order to use a third party package in our Laravel projects.
Install the package
Register the package's service provider
Register facades if any
As you can see, it could be simpler. Now it is.
With automatic package discovery, we'll just require a package and start using it on the fly. Note, however, this only happens if the package provider has configured the package for autodiscovery.
Looking at the Laravel Debugbar package which has already been updated for package autodiscovery, we see that there is an extra section inside the composer.json file:
"extra": { "laravel": { "providers": [ "Foo\\Bar\\ServiceProvider" ], "aliases": { "Bar": "Foo\\Bar\\Facade" } } }
Package providers will have to update the composer.json file with an extra section, then specify the providers and any aliases for the package.
Another good thing with automatic package discovery is that things won't break after removing a dependency. Normally, even after uninstalling a package we still have the package's service providers and facades hanging around in the config/app.php file and this may raise issues in some cases.
With package autodiscovery, when a package is removed via Composer, then everything related to the package is also removed.
Continue reading %What Are the New Features in Laravel 5.5?%
via SitePoint http://ift.tt/2wmD171
0 notes
t-baba · 8 years ago
Photo
Tumblr media
What Are the New Features in Laravel 5.5?
Laravel 5.5 will require PHP 7.0+. For the features this modern PHP version brings, please see our recap.
Laravel 5.5 will also be the next LTS (Long Term Support) release. This means bugfixes for two years and three years of security updates. That was also the case with Laravel 5.1, but its two-year window of bug fixes is coming to an end this year. Without further ado, let's see what this new version has to offer.
Creating a New Laravel 5.5 Project
Since the release has not yet officially happened, we can install the dev release version by running the command:
laravel new laravel55 --dev cd laravel55 php artisan key:generate
If you prefer not to use the Laravel installer, you can also take the Composer approach:
composer create-project --prefer-dist --stability=dev laravel/laravel:dev-master cd laravel php artisan key:generate
Once we visit the homepage of the newly set up app, we should be greeted with a welcome page similar to what we used to have in previous Laravel versions.
Rendering Mailables to the Browser
I feel this is something that will come in very handy. In the previous Laravel versions, we had to send actual emails or use an email client like Mailtrap to test email layouts, and this wasn't a fun task. This won't be the case any more, as with Laravel 5.5 it's possible to render the email layout to the browser directly.
A quick walkthrough on how to achieve this: let's create a new mailable as well as the email template for our current project:
php artisan make:mail Welcome --markdown=emails.welcome
I prefer the markdown approach since we will get a template with some content already. Let's open our web.php file and create a test route to checkout the email layout:
Route::get('/email', function () { return new App\Mail\Welcome(); });
routes/web.php
By visiting the route /email we should be able to preview the email template:
What's actually going on under the hood is that with Laravel 5.5, the Mailable class implements the Renderable contract which has a render() method. This is the implementation of the render() method inside lluminate/Mail/Mailable.php:
public function render() { Container::getInstance()->call([$this, 'build']); return Container::getInstance()->make('mailer')->render( $this->buildView(), $this->buildViewData() ); }
lluminate/Mail/Mailable.php
This is the method that makes it possible to get a view. Had we tried returning an instance of a class that does not implement the Renderable contract within our routes, we'd get an UnexpectedValueException thrown.
Custom Email Themes
When using Markdown for emails, Laravel will provide a default theme. However, some people may prefer having some custom styling in their email templates for branding purposes.
To use a custom theme for a particular mailable, we first create a custom .css file containing the styles we want:
touch resources/views/vendor/mail/html/themes/custom.css
We then then specify this filename as a property in the Mailable class:
class Welcome extends Mailable { protected $theme = 'custom'; [...] }
app/Mail/Welcome.php
This way, the email layout will be based on the styles we defined in the custom.css file. The good thing with this approach is that we can have different themes for different mailables.
Exception Helper Functions
Laravel 5.5 comes with two exception helper functions which will help us write more expressive code. The two helpers are the throw_if and throw_unless methods. Both take three arguments with the third argument being optional.
Let's look at the different implementations of these exceptions:
$number = 2; throw_if($number !== 3, new NotThreeException('Number is not three')); // or throw_if($number !== 3, NotThreeException::class, 'Number is not three');
With the throw_if helper, an exception will be thrown if the first argument evaluates to true.
Implementing the throw_unless helper is no different from what we did above, the only difference being that an exception will only be thrown if the first argument evaluates to false:
$number = 2; throw_unless($number === 3, new NotThreeException('Number is not three')); // or throw_unless($number === 3, NotThreeException::class, 'Number is not three');
Not the best example, but serves our demonstration purposes.
Introducing the migrate:fresh Command
You've probably found yourself in a situation that required you to rebuild the database. With previous Laravel versions, we achieved this by running the php artisan migrate:refresh command. The migrate:refresh command rolls back all migrations based on what is specified in the down method for each migration file then runs the migrations again:
But you've probably run into issues with this command a couple of times, especially when working with foreign key constraints or say you have a down() method in one of your migrations that has not been well defined. When that happens, we resort to dropping the table raising issues manually most of the time - (could be from the CLI or some GUI). That's where migrate:fresh comes to our rescue. This command drops all the tables, then runs the existing migrations again:
JSON Error Stack Traces
Not a really big change but then in previous Laravel versions, we'd see HTML markup from an API client such as Postman every time we got an error while building out APIs. In Laravel 5.5, we get a JSON stack trace rather than HTML markup if an error occurs which looks neater and easier to follow:
Automatic Package Discovery
These are the steps we follow in order to use a third party package in our Laravel projects.
Install the package
Register the package's service provider
Register facades if any
As you can see, it could be simpler. Now it is.
With automatic package discovery, we'll just require a package and start using it on the fly. Note, however, this only happens if the package provider has configured the package for autodiscovery.
Looking at the Laravel Debugbar package which has already been updated for package autodiscovery, we see that there is an extra section inside the composer.json file:
"extra": { "laravel": { "providers": [ "Foo\\Bar\\ServiceProvider" ], "aliases": { "Bar": "Foo\\Bar\\Facade" } } }
Package providers will have to update the composer.json file with an extra section, then specify the providers and any aliases for the package.
Another good thing with automatic package discovery is that things won't break after removing a dependency. Normally, even after uninstalling a package we still have the package's service providers and facades hanging around in the config/app.php file and this may raise issues in some cases.
With package autodiscovery, when a package is removed via Composer, then everything related to the package is also removed.
Continue reading %What Are the New Features in Laravel 5.5?%
by Christopher Vundi via SitePoint http://ift.tt/2u5b5aV
0 notes
mbaljeetsingh · 8 years ago
Text
What's New in Laravel 5.5
At the time of this writing, Laravel 5.5 is not released yet. It is slated, as the next major release, for release in July 2017. To play around with new features and changes, you need to grab the dev release of Laravel using this Laravel Installer command:
laravel new project --dev
Get Ahead with PHP 7.0+
Laravel 5.5 will require PHP 7.0+. Along with developer features, PHP 7 includes speed improvements which will decrease CPU load by half. So, you should definitely make this upgrade. And if you are using Laravel 5, making this upgrade will be a lot easier since you using the latest version of PHP.
The Next LTS (Long Term Support) Release
After Laravel 5.1, Laravel 5.5 is scheduled to be the next LTS release. This includes two years of bug fixes and three years of security updates.
Welcome Back: Whoops!
Whoops, an error-handling framework, which used to be used by Laravel 4, was removed with the release of Laravel 5.0. But with Laravel 5.5, it's coming back pre-installed. What Whoops actually does is that it makes the annoying PHP errors and exceptions a little less annoying by changing how they appear. As you can see in the image that it sports the lines of the file in which the error or exception occurred and traces back the operation till inception. And not forgetting to mention, it has zero dependencies (currently('pre-laravel-55')).
"vendor:publish" Gets a Provider Prompt
In previous versions of Laravel, running the vendor:publish command will publish views, configs, migrations and other resources of all vendors. But in Laravel 5.5, running this command will prompt you to select a provider or tag, making it easier to publish only the ones you want. You can also bypass this prompt by specifying the --all' or '--provider' flag with thepublish` command.
Email Themes
Laravel 5.5 adds the ability to specify a custom theme directly to Mailable classes. You can create a CSS style-sheet like this:
touch resources/views/vendor/mail/html/themes/batman.css
And then specify this filename as a property in your Mailable class.
class SendInvoice extends Mailable { protected $theme = 'batman'; ... }
Rendering Mailables to the Browser
It can be tedious to test your email templates across email clients. One way to test them is to render them to the browser so that you can make instant changes. But it is not an easy task. Luckily, Laravel 5.5 adds the facility to display them directly from your routes.
You can create a Mailable like this:
php artisan make:mail UserWelcome --markdown=emails.user.subscription.canceled
And then render it through a route:
Route::get('/no/way', function () { return new App\Mail\UserSubscriptionCanceled(); });
There are other tools like Litmus, which solve this problem, but they are pretty expensive relative to this tediously trivial task.
Fresh Migrations
Laravel 5.5 adds another Artisan command to the migrate: namespace. This is similar to migrate:refresh but rather than rolling back your existing migrations, it drops all tables and migrates them from start. The difference between rolling back migrations and dropping tables is that rolling back migrations runs the drop method for each of them. Whilst, the migrate:fresh command simply drops all off of the tables and starts from scratch.
Automatic Package Discovery
In Laravel 5.4 and all versions before, pulling a Laravel package required registering its service providers and adding aliases. Laravel 5.5 adds the ability for packages to automatically register service providers and add aliases through the package's composer.json file like this:
"extra": { "laravel": { "providers": [ "The\\Dark\\Knight\\BatmanServiceProvider" ], "aliases": { "Bar": "The\\Dark\\Knight\\Batman" } } }
If you are a package developer, then things can't be much easier for your package users.
Frontend Presets
Out of the box, Laravel includes some CSS and JavaScript scaffolding to help accelerate coding the nitty-gritty. Although you could remove them and start over with your personal preferences, the suggestion was only limited to the Vue framework. Laravel 5.5 introduces 3 frontend presets: Bootstrap, Vue, React and an option choose your own. With Vue being the default preset, you can change the preset to react using this command:
php artisan preset react
You can change react in the above command to vue, bootstrap or none based on your preference.
Error Pages: Design Improvement
In Laravel 5.5, a little change is made in the design of the error pages like 404 or 50* errors: there are some design additions with Flexbox getting the error message centered on the page.
Before Laravel 5.5:
In Laravel 5.5:
Custom Error Reporting
Laravel 5.5 adds support for defining a report method on any custom exception. In Laravel 5.4, you had to check in the Handler class's report method if a particular exception was thrown. So that you could do something like send an email or report to your app's monitoring service. You were doing something like this:
... class Handler extends ExceptionHandler { ... public function report(Exception $exception) { if ($exception instanceof CustomException) { // Send email } parent::report($exception); } }
But with Laravel 5.5, you can get rid of this and register the report method on your custom exception class. Laravel checks to see if there is a report method on your exception class and if it does: calls it.
Streamlined Request Validation
Laravel 5.5 comes with two changes to Request feature. One is that you can now directly call the validate method on your Request instance. So instead of using the controller validator, you can call the validator on your Request instance. You also no longer need to pass the request as the first argument to the validator. Here is an example:
... public function store() { request()->validate([ 'title' => 'required', 'body' => 'required' ]); return Post::create(request(['title', 'body'])); }
The second change made is that the validator returns the request data which you can store in a variable and pass on to the create method of the model.
... public function store() { $post = request()->validate([ 'title' => 'required', 'body' => 'required' ]); // $data = request()->only('title', 'body'); return Post::create($post); }
You need to be careful with this since the data returned by the validator will only contain the fields defined in the rules. This adds a little security but you can loose data if some fields were not defined rules for. To avoid this trap, you can add the field with an empty rule like this:
public function store() { $post = request()->validate([ 'title' => 'required', 'body' => 'required', 'fieldWithNoRules' => '', 'andAnotherOne' => '' ]); // $data = request()->only('title', 'body'); return Post::create($post); }
Exception Helper Functions
Coming to Laravel 5.5 are two new helper functions to help you throw exceptions more elegantly. They are: throw_if and throw_unless, and they do exactly what they say. If you want to throw an exception based on a condition then these may help you reduce a conditional block to a single line. They both accept three arguments with the third being optional. First one is a boolean, second is the exception class and third is the exception message passed in case if you didn't pass with the instantiation of the exception in the second argument. throw_if throws the exception if the boolean is positive and throw_unless throws the exception when the boolean is negative. Here are the examples:
// For `throw_if: $foo = true; throw_if($foo, new BarException('Foo is true')); // or throw_if($foo, BarException::class, 'Foo is true'); // For `throw_unless: $phoo = false; throw_unless($phoo, new BazException('Phoo is false')); // or throw_unless($phoo, BazException::class, 'Phoo is false');
Custom Validation Rules
Laravel 5.5 is coming with a new feature for adding custom validation rules. Custom validation rules are nothing new but with Laravel 5.5 you can have a dedicated class to handle the validation. To define a custom validation rule, you need to create a class with two methods: passes and message. You can place this class anywhere like in the App\Rules namespace. The passes method accepts two arguments: attribute and value, which you can use to validate the field.
<?php namespace App\Rules; use Illuminate\Contracts\Validation\Rule; class CustomRule implements Rule { /** * Determine if the validation rule passes. * * @param string $attribute * @param mixed $value * @return bool */ public function passes($attribute, $value) { // must return true or false for the validation to pass or fail } /** * Get the validation error message. * * @return string */ public function message() { // return a string here for the failing condition } }
Your custom rule should implement the Laravel's Illuminate\Contracts\Validation\Rule contract. You can use this custom validation rule anywhere like in a Form Request class or in the controller validator or the validator from the Request instance. If you are using a custom rule then you can't pass a string with rules separated by a comma. You need to pass each rule as a single element grouped in an array like this:
$request->validate([ 'someField' => [ 'required', 'min:4', new CustomRule() ] ]);
You may also inject any dependency to the constructor if you want. This class-based approach makes custom validation a lot easier.
Model Factory Generators
In Laravel 5.5 you can easily generate model factories with a new Artisan command called make:factory. Here is an example:
php artisan make:factory PostFactory
This will make a new file called PostFactory.php in the database/factories folder. What makes it a lot better is that you can also generate a factory while making a model.
php artisan make:model Post -f
You may also pass the -c flag to add a controller and the -m flag to add a migration. This will help in quickly whipping up a resource.
Miscellany
One minor change is that if you forget to include the CSRF field in a form then it presents you with better inactivity error page. So, if you see something like that, then be sure that it's related to CSRF.
There is another minor change that will help you in building APIs. Now you get a JSON stack trace rather than HTML markup if an error occurs. This makes it a lot prettier to look at rather than the ugly markup if you are using a tool like Postman.
Conclusion
I hope this guide gets you prepared for the forthcoming goodness. So, This is all there is coming to Laravel 5.5.
Happy Coding!
via Scotch.io http://ift.tt/2sfOiDK
0 notes
mbaljeetsingh · 8 years ago
Text
In Laravel 5.5 You Can Render Mailables to the Browser
When you are building custom HTML email templates, it’s typically a chore to test them across all the email clients, and testing them over and over. There are a few tools like Litmus which help solve this problem, but the service is expensive.
Another way to test while you are developing is to render out the email to the browser so you can make quick changes and get almost instant feedback. Although this is a practical use case, rendering Mailables to the browser hasn’t been that simple. That is changing in Laravel 5.5 and these will implement the Renderable Contract allowing you to display them directly from a route.
For example let’s create a UserWelcome Mailable:
php artisan make:mail UserWelcome --markdown=emails.user.welcome
Then, in our routes we can display it like this:
Route::get('/demo', function () { return new App\Mail\UserWelcome(); });
Finally, here is the browser view of this email:
Outside of testing the email through the browser, another use case for this feature is to easily create web views of all the emails you send for when the message is all garbled when it arrives.
This new Render feature will be available with Laravel 5.5 that is due out in July or August. Be sure and join the newsletter to not miss out on the release announcement.
via Laravel News http://ift.tt/2na1Mir
0 notes